from rest_framework.generics import ListAPIView, RetrieveAPIView
from .models import CourseCategory, Course, CourseChapter
from .serializers import CourseCategoryModelSerializer, CourseModelSerializer, CourseDetailModelSerializer, \
    CourseChapterModelSerializer
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from luffy.libs.polyv import PolyvPlayer
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated


# Create your views here.
class StandardPageNumberPagination(PageNumberPagination):
    page_size_query_param = 'page_size'
    max_page_size = 10
    page_size = 5


class CourseCategoryAPIView(ListAPIView):
    queryset = CourseCategory.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseCategoryModelSerializer


class CourseAPIView(ListAPIView):
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseModelSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filter_fields = ('course_category',)
    ordering_fields = ('id', 'students', 'price')
    pagination_class = StandardPageNumberPagination


class CourseDetailAPIView(RetrieveAPIView):
    queryset = Course.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseDetailModelSerializer


class CourseChapterAPIView(ListAPIView):
    queryset = CourseChapter.objects.filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseChapterModelSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']


class PolyvAPIView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        vid = request.query_params.get('vid')
        remote_addr = request.META.get('REMOTE_ADDR')
        user_id = request.user.id
        user_name = request.user.username
        polyv_video = PolyvPlayer()
        verify_data = polyv_video.get_video_token(vid, remote_addr, user_id, user_name)
        return Response(verify_data['token'])
